import React,{ Component } from 'react';
import { connect } from 'react-redux';
import { Form, Affix, Button, Input, Radio, Select, InputNumber, DatePicker, Spin, message } from 'antd';
import {messages} from "share/common";
import chooserData from 'share/chooserData';
import Chooser from 'components/chooser';
import EnhanceSelectEmployee from 'components/template/enhance-select-employee/index';
import 'styles/supplier-management/overview/yget-quota-adjust.scss';
import DetailSever from 'containers/supplier-management/overview/supplier-detail/supplier-detail.service'
import moment from 'moment';

const FormItem = Form.Item;
const Group = Radio.Group;
const Option = Select.Option;
const InputGroup = Input.Group;

class NewQuotaAdjust extends Component{

  submitLock = false;

  constructor(props){
    super(props);
    this.state = {
      status:'create',
      editItem:{},
      submitting: false,
      chooserItem:[],
      selectGroupOid:[],
      groupVisible:false,
    }
  }

  componentWillMount(){
    this.setState({chooserItem:chooserData['user_all']});
  }

  componentWillReceiveProps(nextProps){
    const edit = nextProps.params.editItem;
    if(this.state.status === 'create' && edit && edit.creditOID){
      let item = {
        creditOID:edit.creditOID,
        effectDate:edit.effectDate,
        actionType:'users',
        addOrSub: edit.limitAccount >= 0 ? 'add' : 'sub',
        limitAccount:Math.abs(edit.limitAccount),
        actionList:edit.actionList.map(de => de.actionOID),
      };
      this.setState({status:'edit',editItem:item},()=>{
        this.props.form.resetFields();
      })
    }
  }

  toSubmit = () => {
    if(this.submitLock){
      return;
    }else{
      this.submitLock = true;
    }
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        if(values.userGroup.length <= 0){
          message.error(messages('supplier.key205')/*请选择操作人员*/);
          this.submitLock = false;
          return;
        }
        const params = {
          creditOID:values.creditOID,
          effectDate:values.effectDate.format('YYYY-MM-DD'),
          actionType:values.actionType,
          limitAccount:values.addOrSub === 'add' ? values.limitAccount : -values.limitAccount,
          actionList: values.userGroup.map(item => {
            return {
              action: item.fullName || item.name,
              actionOID: item.userOID || item.userGroupOID,
            }
          })
        };
        this.setState({submitting: true});
        DetailSever.ygetAdjustCommit(params).then(res => {
          if(res.status === 200){
            this.closeSlide(true);
          }
        }).catch(err => {
          message.error(err.response.data.message);
        })
      }else{
        if(err.limitAccount && err.limitAccount.errors[0]){
          message.error(err.limitAccount.errors[0].message);
        }
        this.submitLock = false;
      }
    });
  }

  // 关闭侧滑
  closeSlide = (isUpdate) => {
    this.props.close(isUpdate);
    this.submitLock = false;
    delete this.props.params.editItem;
    this.props.form.resetFields();
    this.setState({submitting: false, status:'create', editItem:{}});
  }

  witchOperator = () => {
    const operator = this.props.form.getFieldValue('actionType');
    const { getFieldDecorator } = this.props.form;
    const { chooserItem, editItem } = this.state;
    if(operator === 'users'){
      return (
        <FormItem style={{marginLeft: '33.3%',width: '60%'}}>
          {getFieldDecorator('userGroup',{
              initialValue:editItem.actionList || [],
            }
          )(
            <Chooser selectorItem={chooserItem}
                     valueKey="userOID"
                     labelKey="fullName"
                     placeholder={messages('common.please.select'/*请选择*/)}
                     newline={true}
            />
          )}
        </FormItem>
      )
    }else if( operator === 'groups'){
      return (
        <FormItem style={{marginLeft: '33.3%',width: '60%'}}>
          {
            getFieldDecorator('userGroup',{
              initialValue:editItem.actionList || [],
            })(
              <EnhanceSelectEmployee entity={true} mode={{key:'userGroupOID', label:'name'}}/>
            )
          }
        </FormItem>
      );
    }
  }

  disabledDateEnd(current){
    let boo = false;
    let startDate = moment(new Date()).format('YYYY-MM-DD');
    if(current < moment(startDate))
      boo = true;
    return current && boo;
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { submitting, editItem } = this.state;
    const layout = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    }
    return(
      <div className='yget-quota-adjust'>
        <Spin spinning={submitting}>
          <Form>
            {
              editItem.creditOID && <FormItem {...layout} label={messages('supplier.key196')/*事务ID*/}>
                {
                  getFieldDecorator('creditOID',{
                    initialValue: editItem.creditOID || '',
                  })(
                    <Input disabled/>
                  )
                }
              </FormItem>
            }
            <FormItem {...layout} label={messages('supplier.key206')/*操作人员*/}>
              {
                getFieldDecorator('actionType',{
                  initialValue:editItem.actionType || '',
                  rules:[{
                    required:true,
                    message:messages('supplier.key205')/*请选择操作人员*/,
                  }]
                })(
                  <Group>
                    <Radio value={'users'}>{messages('budget.key87')/*人员*/}</Radio>
                    <Radio value={'groups'}>{messages('menu.person-group')/*人员组*/}</Radio>
                  </Group>
                )
              }
            </FormItem>
            {this.witchOperator(layout)}
            <FormItem {...layout} label={messages('supplier.key207')/*额度调整*/}>
              <InputGroup compact>
                {
                  getFieldDecorator('addOrSub',{
                    initialValue:editItem.addOrSub || 'add',
                    rules:[{
                      required:true,
                    }]
                  })(
                    <Select>
                      <Option value="add">{messages('supplier.key208')/*增加*/}</Option>
                      <Option value="sub">{messages('supplier.key209')/*减少*/}</Option>
                    </Select>
                  )
                }
                {
                  getFieldDecorator('limitAccount',{
                    initialValue:editItem.limitAccount || 0,
                    rules:[{
                      required:true,
                      message:messages('supplier.key210')/*请填写额度*/
                    }]
                  })(
                    <InputNumber min={0} precision={0.1} style={{ width: '50%' }}/>
                  )
                }
              </InputGroup>
            </FormItem>
            <FormItem {...layout} label={messages('supplier.key200')/*生效日期*/}>
              {
                getFieldDecorator('effectDate',{
                  initialValue:editItem.effectDate ? moment(editItem.effectDate) : null,
                  rules:[{
                    required:true,
                    message:messages('supplier.key211')/*请填写生效日期*/
                  }]
                })(
                  <DatePicker disabledDate={this.disabledDateEnd}/>
                )
              }
            </FormItem>
          </Form>
        </Spin>
        <Affix className='slide-affix' offsetBottom={0}>
          <Button onClick={this.toSubmit} type="primary" loading={submitting}>{messages('request.key211'/*确定*/)}</Button>
          <Button onClick={this.closeSlide} >{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const wrapperNewQuotaAdjust = Form.create()(NewQuotaAdjust);

export default connect(mapStateToProps)(wrapperNewQuotaAdjust);

